// stores/permission.js
import { defineStore } from 'pinia'
import { authRoutes } from '@/router/routes'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    isReady: false // 新增路由就绪状态
  }),

  actions: {
    async generateRoutes(roles) {
      try {
        // 添加角色参数处理
        const filteredRoutes = filterAsyncRoutes(authRoutes, roles)
        this.routes = filteredRoutes
        this.isReady = true
      } catch (error) {
        console.error('路由生成失败:', error)
      }
    }
  }
})

// 实现具体的过滤逻辑
function filterAsyncRoutes(routes, roles) {
  return routes.filter(route => {
    // 添加角色权限检查
    const hasPermission = !route.meta?.roles || route.meta.roles.some(r => roles.includes(r))
    const validChildren = route.children?.length ? filterAsyncRoutes(route.children, roles) : []
    return hasPermission && validChildren.length || route.component
  })
}
